package com.fas.hehe.system.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.csource.common.NameValuePair;

import com.fas.core.Service;
import com.fas.core.plugin.fastdfs.FastDFSManager;
import com.fas.core.util.DateFormatFactory;
import com.fas.core.util.sequence.Sequence;
import com.fas.hehe.system.model.Attach;
import com.jfinal.upload.UploadFile;

public class AttachService extends Service {

	public List<Attach> uploadFile(List<UploadFile> files) throws Exception {

		Date now = new Date();
		String month = DateFormatFactory.getInstance("yyyyMM").format(now);

		List<Attach> attachList = new ArrayList<Attach>();
		if (CollectionUtils.isNotEmpty(files)) {
			for (UploadFile uploadFile : files) {

				File tempFile = uploadFile.getFile();
				String filename = uploadFile.getFileName();
				String contentType = uploadFile.getContentType();

				// 2. 服务端临时文件上传到FastDFS
				List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
				nvpList.add(new NameValuePair("filename", filename));
				nvpList.add(new NameValuePair("filesize", String.valueOf(tempFile.length())));
				nvpList.add(new NameValuePair("contenttype", uploadFile.getContentType()));

				log.info("准备上传文件"+filename+"(本地："+tempFile.getCanonicalPath()+")到FastDFS...");
				String savePath = FastDFSManager.uploadFile(tempFile, nvpList.toArray(new NameValuePair[0]));
				log.info("文件"+filename+"(远程："+tempFile.getCanonicalPath()+")成功上传FastDFS");

				// 4. 记录到库表【附件表】
				Attach attach = new Attach();
				Long attId =Sequence.getSequence();
				attach.setAttId(attId);
				attach.setFileName(filename);
				attach.setSaveMonth(month);
				attach.setSavePath(savePath);
				attach.setContentType(contentType);
				attach.setUploadTime(now);
				attach.setServiceCode("");//TODO
				attach.setCompanyId(this.getCompanyId());
				attach.setUserId(this.getLoginUser().getUserId()+"");
				attach.setMemo("");

				attach.save();
				log.info("附件"+attId+" , 远程:"+tempFile.getCanonicalPath()+" 入库成功");
				
				attachList.add(attach);
			}
		}
		return attachList;
	}
	
	public boolean deleteFile(String savepath) throws Exception {
		String sql = "select * from sys_attach where company_id=? and save_path=?";
		Attach attach = Attach.dao.findFirst(sql, this.getCompanyId(),savepath);
		String filename = attach.getFileName();
		
		log.info("准备删除文件"+filename+", FastDFS远程文件"+savepath);
		int  statusCode = FastDFSManager.deleteFile(savepath);
		if(statusCode ==0){
			attach.delete();
			log.info("删除文件"+filename+"成功, FastDFS远程文件"+savepath);
			return true;
		}else{
			log.info("删除文件"+filename+"失败, FastDFS远程文件"+savepath);
			return false;
		}
	}
}
